#include <psp2/kernel/clib.h>
#include <psp2/io/dirent.h>
#include <psp2/io/fcntl.h>
#include <psp2/io/stat.h>

#include "utils.h"

int file_exists(const char *path)
{
    SceIoStat stat;

    if (sceIoGetstat(path, &stat) < 0)
        return 0;
    else
        return 1;
}

int read_file(const char *file, void *buffer, int size)
{
    SceUID fd = sceIoOpen(file, SCE_O_RDONLY, 0);
    if (fd < 0)
        return fd;

    int read = sceIoRead(fd, buffer, size);
    sceIoClose(fd);

    return read;
}

int write_file(const char *file, const void *buffer, int size)
{
    SceUID fd = sceIoOpen(file, SCE_O_WRONLY | SCE_O_CREAT | SCE_O_TRUNC, 0777);
    if (fd < 0)
        return fd;

    int written = sceIoWrite(fd, buffer, size);

    sceIoClose(fd);
    return written;
}

int remove_file(const char *path)
{
    SceUID dfd = sceIoDopen(path);
    if (dfd >= 0)
    {
        int res = 0;

        do
        {
            SceIoDirent dir;
            sceClibMemset(&dir, 0, sizeof(SceIoDirent));

            res = sceIoDread(dfd, &dir);
            if (res > 0)
            {
                char new_path[256];
                sceClibSnprintf(new_path, sizeof(new_path), "%s/%s", path, dir.d_name);
                res = remove_file(new_path);
            }
        } while (res > 0);

        sceIoDclose(dfd);

        return sceIoRmdir(path);
    }

    return sceIoRemove(path);
}
